package com.example.okhttp;

import com.okhttp.cache.CacheControl;
import com.okhttp.cache.CacheInterceptor;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Request.Builder;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author GYL
 * @dateTime 2020/4/16-13:49
 * @description
 */
public class OkhttpManager {
  
  private OkHttpClient client;
  
  private OkhttpManager() {
    // 缓存目录
    //File file = new File(Environment.getExternalStorageDirectory(), "a_cache");
    // 缓存大小
    //int cacheSize = 10 * 1024 * 1024;
    
    client = new OkHttpClient.Builder()
               //.cache(Config.makeCache())
               //.addNetworkInterceptor(new NetInterceptor(App.getInstance()))
               //.addInterceptor(new NoNetInterceptor(App.getInstance()))
               .addInterceptor(new CacheInterceptor())
               .connectTimeout(10, TimeUnit.SECONDS)
               .writeTimeout(10, TimeUnit.SECONDS)
               .readTimeout(10, TimeUnit.SECONDS)
               .build();
  }
  
  public static OkhttpManager getInstance() {
    return OkHttpHolder.instance;
  }
  
  private static class OkHttpHolder {
    
    private static final OkhttpManager instance = new OkhttpManager();
  }
  
  public void request(final Callback callback,String param,String method) {
    final Request request ;
    Builder builder = new Builder();
                        //.cacheControl(CacheControl.FORCE_NETWORK);
    
    builder.addHeader(CacheControl.CACHE_HEADER_TAG,CacheControl.FIRST_NET+"")
      .addHeader(CacheControl.CACHE_HEADER_EXPIRE_TAG,1*1000*60+"");
    if("POST".equals(method)){
      RequestBody body=new FormBody.Builder(Charset.defaultCharset()).add("test",param).build();
      request=builder.url("http://192.168.10.78:3001/city")
        .post(body).build();
    }else{
      request=builder.url("http://192.168.10.78:3001/city?test="+param)
                .get().build();
    }
    client.newCall(request).enqueue(new Callback(){
      @Override
      public void onFailure(Call call, IOException e) {
//        client.cache().directory();
//        Builder builder2= request.newBuilder();
//        builder2.cacheControl(CacheControl.FORCE_CACHE);
//        requestCache(callback,builder2.build());
        callback.onFailure(call,e);
      }
  
      @Override
      public void onResponse(Call call, Response response) throws IOException {
        callback.onResponse(call,response);
      }
    });
    
  }
  
  
  private void requestCache(final Callback callback,Request cacheRequest){
    System.out.println("只请求cacahe......");
    client.newCall(cacheRequest).enqueue(callback);
  }
  
}
